package model;

import javax.jms.JMSException;
import javax.jms.Message;

import org.apache.qpid.client.message.JMSTextMessage;

import users.Subscriber;
import users.SubscriberMessageListener;

/**
 * Listener to messages from other application clients.
 */
public class ReaderMessageListener extends SubscriberMessageListener {

    /**
     * Constructor.
     *
     * @param sub  sub to which this message listener belongs
     */
    public ReaderMessageListener(final Subscriber sub) {
        super(sub);
    }

    /**
     * Getter for the variable 'sub'.
     * @return variable 'sub' as a reader
     */
    public Reader getSub() {
        return (Reader) super.getSub();
    }

    /**
     * This method is asynchronously executed when a message from an
     * application client is received.
     *
     * @param msg  received message
     */
    @Override
    public void onMessage(final Message msg) {

        //let Subscriber deal with mirror subscribers and duplicate messages
        super.onMessage(msg);

        if (!super.isLastMsgDup()) {
            try {

                JMSTextMessage message = (JMSTextMessage) msg;
//                getPendingMsgs().add(message);
//                setNumMsgs(getPendingMsgs().size());
                String msgInfo = message.getJMSTimestamp() + ";"
                        + message.getJMSMessageID() + ";" + message.getText()
                        + ";" + message.getStringProperty("header");
                getSub().getPendingMsgsInfo().add(msgInfo);
                getSub().setNumMsgs(getSub().getPendingMsgsInfo().size());

            } catch (JMSException e) {
                System.err.println("Error receiving message: " + e);
            }
        }

    }

}
